package com.admin.system.modules.system.rest;

import cn.hutool.core.collection.CollectionUtil;
import com.admin.common.constant.ExceptionConstant;
import com.admin.common.entity.BaseEntity;
import com.admin.common.exception.BadRequestException;
import com.admin.common.utils.PageResult;
import com.admin.component.web.MultipartFileUtil;
import com.admin.core.dto.DictQueryDTO;
import com.admin.core.entity.SysDict;
import com.admin.core.entity.SysDictDetail;
import com.admin.logging.annotation.Log;
import com.admin.logging.enums.OperateTypeEnum;
import com.admin.system.modules.system.service.DictDetailService;
import com.admin.system.modules.system.service.DictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author sq-lan
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "系统：字典管理")
@RequestMapping("/api/dict")
public class DictController {

    private final DictService dictService;
    private final DictDetailService dictDetailService;

    @ApiOperation("查询字典")
    @GetMapping
    @PreAuthorize("@ss.check('dict:list')")
    public ResponseEntity<PageResult<SysDict>> paging(DictQueryDTO entity) {
        return new ResponseEntity<>(dictService.paging(entity), HttpStatus.OK);
    }

    @ApiOperation("查询字典")
    @GetMapping(value = "/all")
    @PreAuthorize("@ss.check('dict:list')")
    public ResponseEntity<List<SysDict>> list() {
        return new ResponseEntity<>(dictService.list(new DictQueryDTO()), HttpStatus.OK);
    }

    @Log(module = "字典管理", operateType = OperateTypeEnum.ADD)
    @ApiOperation("新增字典")
    @PostMapping
    @PreAuthorize("@ss.check('dict:add')")
    public ResponseEntity<Object> add(@Validated @RequestBody SysDict entity) {
        if (entity.getId() != null) {
            throw new BadRequestException(ExceptionConstant.ERROR_PARAM);
        }
        dictService.save(entity);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @Log(module = "字典管理", operateType = OperateTypeEnum.MODIFY)
    @ApiOperation("修改字典")
    @PutMapping
    @PreAuthorize("@ss.check('dict:edit')")
    public ResponseEntity<Object> modify(@Validated(BaseEntity.Update.class) @RequestBody SysDict entity) {
        dictService.updateById(entity);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log(module = "字典管理", operateType = OperateTypeEnum.REMOVE)
    @ApiOperation("删除字典")
    @DeleteMapping
    @PreAuthorize("@ss.check('dict:del')")
    public ResponseEntity<Object> remove(@RequestBody Set<Long> ids) {
        dictService.remove(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("导出字典数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@ss.check('dict:list')")
    public void export(HttpServletResponse response, DictQueryDTO dto) throws IOException {
        List<SysDict> list = dictService.list(dto);
        List<SysDictDetail> listDetail = dictDetailService.list();
        Map<Integer, List<SysDictDetail>> detailMap = listDetail.stream().collect(Collectors.groupingBy(SysDictDetail::getDictId));
        List<Map<String, Object>> result = new ArrayList<>();
        for (SysDict dict : list) {
            if (CollectionUtil.isNotEmpty(detailMap.get(dict.getId()))) {
                for (SysDictDetail dictDetail : detailMap.get(dict.getId())) {
                    Map<String, Object> map = new LinkedHashMap<>();
                    map.put("字典名称", dict.getName());
                    map.put("字典描述", dict.getDescription());
                    map.put("字典标签", dictDetail.getLabel());
                    map.put("字典值", dictDetail.getValue());
                    map.put("创建日期", dictDetail.getCreateTime());
                    result.add(map);
                }
                continue;
            }

            Map<String, Object> map = new LinkedHashMap<>();
            map.put("字典名称", dict.getName());
            map.put("字典描述", dict.getDescription());
            map.put("字典标签", null);
            map.put("字典值", null);
            map.put("创建日期", dict.getCreateTime());
            result.add(map);
        }
        MultipartFileUtil.downloadExcel(result, response);
    }

}
